﻿namespace RockPaperScissors.IronPython
{
    using System.IO;
    using System.Reflection;
    using global::IronPython.Hosting;
    using GravityWorks.RockPaperScissors.Toolkit;
    using Microsoft.Scripting.Hosting;

    public class IronPythonWrapper : IPlayer
    {
        dynamic player;

        public IronPythonWrapper()
        {
            ScriptEngine engine = Python.CreateEngine();
            string[] paths = new string[] { };
            engine.SetSearchPaths(paths);
            Assembly asm = Assembly.GetExecutingAssembly();
            StreamReader reader = new StreamReader(asm.GetManifestResourceStream("RockPaperScissors.IronPython.IronPythonPlayer.py"));

            string script = reader.ReadToEnd();
            ScriptSource source = engine.CreateScriptSourceFromString(script);
            ScriptScope scope = engine.CreateScope();
            ObjectOperations op = engine.Operations;
            source.Execute(scope);
            dynamic playerType = scope.GetVariable("player");
            player = playerType();
        }

        public MoveType Shoot(GameLog gameLog, RuleSet rules, int round)
        {
            object shot = player.Shoot(gameLog, rules, round);
            return (MoveType)shot;
        }
    }
}
